/* MIT License
 *
 * Copyright (c) 2012 Reuben Smith, Miami University
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.droidlike.vsig;


import com.jme3.app.Application;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.collision.CollisionResults;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JTable;


// BUGD As soon as Simulation is created and has focus, key accelerators are not
//      passed to Swing. Maybe something with jME input glomming all inputs? For 
//      now don't use shortcuts.


/**
 * Simulation.
 *
 * @author smithre5
 */
public class Simulation
        extends Application
{
    public Simulation(VSIGFrame frame, long seed)
    {
        super();
        
        this.frame = frame;
        
        if (seed > Long.MIN_VALUE) {
            random = new Random(seed);
        }
        else {
            random = new Random();
        }
        
        executor = ExecutorService.create(VSIG.SERVICE_PATH, VSIG.STORAGE_PATH);
        if (executor == null) {
            JOptionPane.showMessageDialog(
                null, 
                "Failed to create executor service. Exiting.", 
                VSIG.TITLE, 
                JOptionPane.ERROR_MESSAGE
            );
            System.exit(-1);
        }
        
        agents = new ArrayList<Agent>(32);
        signals = new HashMap<RoadNode, TrafficSignal>();
    }
    
    
    /**
     * Binds a node and signal together.
     * 
     * @param node the node to be bound
     */
    public boolean bindSignal(RoadNode node, TrafficSignal signal)
    {
        if (node == null || signal == null || roads.getNode(node.getPosition()) == null ||
            signals.get(node) != null) {
            return false;
        }
        
        signals.put(node, signal);
        return true;
    }
 
    
    public TrafficSignal getSignal(RoadNode node)
    {
        return signals.get(node);
    }
    
    
    public boolean hasSignal(RoadNode node)
    {
        return signals.get(node) != null;
    }
    
    
    public void createAgent(Vector3f position)
    {
        Agent agent = Agent.createAttachedAt(this, position);
        agents.add(agent);
    }
    
    
    public void removeAgent(Agent agent)
    {
        if (agent == null) {
            return;
        }
        
        System.out.println(agent.getSpatial().getName() + " going down!");
        
        agents.remove(agent);
        scene3D.detachChild(agent.getSpatial());
        agent.getSpatial().removeControl(agent);
    }
    
    
    public boolean willCollide(Agent agent)
    {
        if (agent == null) {
            return false;
        }
        
        CollisionResults collisions = new CollisionResults();
        
        for (Agent otherAgent : agents) {
            if (agent == otherAgent) {
                continue;
            }
            
            agent.getSpatial().collideWith(otherAgent.getSpatial().getWorldBound(), collisions);
            if (collisions.size() > 0) {
                return true;
            }
        }
        
        return false;
    }


    @Override
    public void initialize()
    {
        super.initialize();
        
        createScenes();
        createCamera();        
        
        physics = new BulletAppState();
        stateManager.attach(physics);
        physics.getPhysicsSpace().setGravity(new Vector3f(0, -32.2f, 0));
        
        // TODO Map loading/generation.
        createTestWorld();
        
        addInputs();
        
        tool = Tool.create(this);
        tool.attachUI();
    }
    
    
    @Override
    public void update()
    {
        super.update();
        
        if (speed == 0 || paused) {
            return;
        }
        
        float tpf = speed * timer.getTimePerFrame();
        
        stateManager.update(tpf);
        
        tool.placeUI();
        
        scene3D.updateLogicalState(tpf);
        scene2D.updateLogicalState(tpf);
        scene3D.updateGeometricState();
        scene2D.updateGeometricState();
        
        stateManager.render(renderManager);
        renderManager.render(tpf, context.isRenderable());
        // this.render();
        stateManager.postRender();
    }
    

    /**
     * @return the service used by the sim
     */
    public ExecutorService getExecutorService()
    {
        return executor;
    }
    
    
    /**
     * @return the table for entity information
     */
    public JTable getInfoTable()
    {
        return frame.getTable();
    }
    
    
    /**
     * @return graph of the road system
     */
    public RoadGraph getGraph()
    {
        return roads;
    }
    
    
    public Random getRandom()
    {
        return random;
    }
    
    
    /**
     * @return node for 2D scene
     */
    public Node getScene2D()
    {
        return scene2D;
    }
    
    
    /**
     * @return node for 3D scene
     */
    public Node getScene3D()
    {
        return scene3D;
    }

       
    /**
     * Returns the simulation camera controller.
     * 
     * @return the controller
     */
    public SimulationCamera getSimulationCamera()
    {
        return stateManager.getState(SimulationCamera.class);
    }
    
    
    public PhysicsSpace getSpace()
    {
        return physics.getPhysicsSpace();
    }
    
    
    /**
     * Maps and listens for simulation inputs.
     */
    private void addInputs()
    {
        Profile profile = VSIG.getProfile();
        
        inputManager.addMapping("ToggleDebug", new KeyTrigger(
            Integer.parseInt(profile.getValue("input.debug"))));
        
        inputManager.addListener(new ActionListener() {
            public void onAction(String name, boolean pressed, float tpf)
            {
                if (name.equals("ToggleDebug") && !pressed) {
                    VSIG.toggleDebugMode();
                }
            }
        }, new String[] {
            "ToggleDebug"
        });
    }
    
    
    /**
     * Creates and attaches a SimulationCamera.
     */
    private void createCamera()
    {
        stateManager.attach(new SimulationCamera(this, World.BOUNDS));
    }
    
    
    /**
     * Creates the 2D and 3D scene nodes and attaches them.
     */
    private void createScenes()
    {
        scene2D = new Node("scene2DNode");
        scene2D.setQueueBucket(RenderQueue.Bucket.Gui);
        scene2D.setCullHint(Spatial.CullHint.Never);
        guiViewPort.attachScene(scene2D);
        
        scene3D = new Node("scene3D");
        viewPort.attachScene(scene3D);
    }
    
    
    /**
     * Creates and attaches a simple crossroads world for testing.
     */
    private void createTestWorld()
    {
        /*
         * Creates a simple crossroads:
         * 
         *       0
         *       |
         *       1
         *      /|\
         * 6---7---5---4
         *      \|/
         *       3
         *       |
         *       2
         */
        
        // smithre5: This is from a generic vehicle length of 18 ft. This should
        // probably be generated...
        
        // Separation (in feet) of the nodes leading into the intersection. 
        float intersectionSize = 36.0f;
        roads = RoadGraph.create(
            new RoadNode[]{
                RoadNode.create(new Vector3f(0, 0, World.BOUNDS[0].z), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(0, 0, -intersectionSize), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(0, 0, World.BOUNDS[1].z), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(0, 0, intersectionSize), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(World.BOUNDS[1].x, 0, 0), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(intersectionSize, 0, 0), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(World.BOUNDS[0].x, 0, 0), Vector3f.UNIT_Y, 1, 12.0f),
                RoadNode.create(new Vector3f(-intersectionSize, 0, 0), Vector3f.UNIT_Y, 1, 12.0f),
            },
            new int[][]{
                {0, 1}, {2, 3}, {4, 5}, {6, 7},
                {1, 5, 7}, {3, 5, 7},
                {1, 3}, {5, 7}
            }
        );
        
        world = new World(physics.getPhysicsSpace());
        viewPort.setBackgroundColor(World.SKY_COLOR);
        stateManager.attach(world);
    }    
    
    
    private VSIGFrame frame;
    
    private Random random;
    private ExecutorService executor;
    
    private Node scene2D;
    private Node scene3D;
    private Tool tool;
    
    private BulletAppState physics;
    private World world;
    private RoadGraph roads;
    
    private ArrayList<Agent> agents;
    private HashMap<RoadNode, TrafficSignal> signals;
}

